//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;
using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CA = ComponentArt.Web.UI;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;

namespace CommunityServer.ControlPanel.BlogAdmin
{
	/// <summary>
	///		Summary description for BlogListControl.
	/// </summary>
	public class BlogListControl : BaseBlogAdminGridControl
	{

		#region Child Controls

		protected CA.Grid Grid1;
		protected CheckBox chkConfirmInsert;
		protected CheckBox chkConfirmUpdate;
		protected CheckBox chkConfirmDelete;
		protected Modal Modal1;
		protected ResourceControl FeedbackFilterLabel;
		protected DropDownList AdminGroupList;
		protected Controls.ResourceControl Resourcecontrol1;

		#endregion

		protected int groupID = CSContext.Current.GetIntFromQueryString("GroupID",-1);
		private bool IsEdit = true;

		private bool HasGroupFilter
		{
			get{return groupID != -1;}
		}

		private void Page_Load(object sender, EventArgs e)
		{

			if(!Page.IsPostBack && !BlogAdminPage.IsCallBack)
			{
				BindGroupList();
				ConfigurePage();
				buildGrid();
				Grid.DataBind();
			}

		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			this.AdminGroupList.SelectedIndexChanged += new EventHandler(this.AdminGroupList_SelectedIndexChanged);
			this.Grid.DeleteCommand += new CA.Grid.GridItemEventHandler(this.Grid_DeleteCommand);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new EventHandler(this.Page_Load);
			this.EnableSearchBox = true;
		}
		#endregion

		private void BindGroupList()
		{
			ArrayList groups = WeblogGroups.GetWeblogGroups(true, true, true);
			foreach(Group group in groups)
				AdminGroupList.Items.Add(new ListItem(group.Name, group.GroupID.ToString()));
	
			AdminGroupList.Items.Insert(0,new ListItem(ResourceManager.GetString("CP_BlogAdmin_Blogs_AllGroups"),"-1"));
		}

		private void ConfigurePage()
		{

			ListItem li = AdminGroupList.Items.FindByValue(groupID.ToString());
			if(li != null)
				li.Selected = true;
              
		}
		private void UpdateDb(CA.GridItem item, string command)
		{
			//Check to see that the user can administer
			//Ideally we will add conditional formatting on the grid to hide these options too
			if(!CSContext.Current.User.IsBlogAdministrator)
				throw new CSException( CSExceptionType.AdministrationAccessDenied );

			this.IsEdit = true;
			Weblog blog;
			switch (command)
			{
				case "DELETE":
					
					blog = Weblogs.GetWeblog(int.Parse(item["SectionID"].ToString()), false) ;
					
					Weblogs.Delete( blog ) ;

					break;

				default: 
					throw new NotImplementedException(string.Concat("The {0} command has not yet been implemented!" ,command)); 
			}
		}

		private void Grid_DeleteCommand(object sender, CA.GridItemEventArgs e)
		{
			UpdateDb(e.Item, "DELETE"); 
		}


		protected override void buildGrid()
		{
			ArrayList sections = GetWeblogs();

			sections = Sections.FilterByAccessControl(sections, Permission.Administer, CSContext.Current.User);
	

			//The grid will only show checkboxes in edit mode if the data source is a DataTable
			DataTable dt = CADataConverter.ToDataTable(sections, typeof(Weblog));
			dt.DefaultView.Sort = "ApplicationKey";
			Grid.DataSource = dt;

			this.RecordCount = dt.Rows.Count;

			ApplyUserSettings();

			if(this.EnableGrouping)
			{
				dt.DefaultView.Sort = "GroupName";
				Grid.GroupBy = "GroupName ASC";
			}

		}

		private void AdminGroupList_SelectedIndexChanged(object sender, EventArgs e)
		{
			//TODO: Figure out how to use a CA filter and dump this hack
			//Grid.CurrentPageIndex = 0;
			//Grid.DataBind();
			
			string url  = "{0}?GroupID={1}";
			url = string.Format(url, Request.Path, AdminGroupList.SelectedValue);
			Response.Redirect(url);

		}

		protected ArrayList GetWeblogs()
		{
			if(HasGroupFilter)
				return Weblogs.GetWeblogsByGroupID(groupID, true, true, this.IsEdit);
			else
				return Weblogs.GetWeblogs(true, true, this.IsEdit);

		}

		protected ArrayList GetGroups()
		{
			return WeblogGroups.GetWeblogGroups(false, true, true);
		}

		protected override void ConfigureGrid()
		{
			AddGridCheckMarkTemplate("IsActive");
			string sectionURL = @"SectionEdit.aspx?tab=blog&amp;SectionID=## DataItem.GetMember(""SectionID"").Text ##";
			AddGridHrefTemplate(sectionURL,"","Name", @"## DataItem.GetMember(""Description"").Text ##");
			AddGridHrefTemplate(sectionURL,"ApplicationKey");
			
			AddGridPagerTemplate("Name", "GroupName","IsActive");
		}


	}
}
